package cn.yi.fast.mq.rocketmq.yml;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 解析yaml文件，获取topic与Tag之间的关系Map
 */
public class YmlDefaultSubscribeMapFactoryBean implements FactoryBean<Map<String, String>>, InitializingBean {

    private Map<String, Object> ymlMap;

    private Map<String, String> topic2TagMap;

    public void setYmlMap(Map<String, Object> ymlMap) {
        this.ymlMap = ymlMap;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initHandler(ymlMap);
    }

    private void initHandler(Map<String, Object> ymlMap) {
        topic2TagMap = new HashMap<>();
        ymlMap.forEach((key, value) -> {
            if (key.startsWith("[") && key.endsWith("]")) {
                key = key.substring(1, key.length() - 1);
                for (String topic : Splitter.on("|").splitToList(key)) {
                    topic2TagMap.put(topic, Joiner.on(" || ").join(Splitter.on("|").splitToList(Objects.toString(value))));
                }
            }
        });
    }


    @Override
    public Map<String, String> getObject() throws Exception {
        return topic2TagMap;
    }

    @Override
    public Class<?> getObjectType() {
        return Map.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

